package main

import (
	"html/template"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strings"
	"fmt"
	"os"
	"github.com/russross/blackfriday"
)

type Post struct {
	Title   string
	Date    string
	Summary string
	Body    string
	File    string
}

func handlerequest(w http.ResponseWriter, r *http.Request) {

	if r.URL.Path == "/" {
		posts := getPosts()
		t := template.New("index.html")
		t, _ = t.ParseFiles("index.html")
		t.Execute(w, posts)
	}else{

		file_name:=strings.Replace( r.URL.Path ,"/","",1)

		var file string
		if strings.Contains(file_name,".md"){
			file=fmt.Sprintf("Golang/%s",string(file_name))
		}else{
			file=fmt.Sprintf("Golang/%s.md",string(file_name))
		}

		_,err:=os.Stat(file)

		if err!=nil{
			fmt.Println(err)
			w.WriteHeader(404)
			return
		}
		txt,err:=ioutil.ReadFile(file)
		output := blackfriday.MarkdownCommon(txt)
		w.WriteHeader(http.StatusOK)
		w.Header().Set("Content-Type:text/html", "charset=utf-8")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Action, Module")   //有使用自定义头 需要这个,Action, Module是例子
		fmt.Fprint(w,string(output))
		//w.Write(output)
	}
}

func getPosts() []Post {
	a := []Post{}
	files, _ := filepath.Glob("Golang/*.md")
	fmt.Println(files)
	for _, f := range files {
		file := strings.Replace(f, "Golang\\", "", -1)
		fmt.Println(file)
		file = strings.Replace(file, ".md", "", -1)
		fileread, _ := ioutil.ReadFile(f)
		lines := strings.Split(string(fileread), "\n")
		title := string(lines[0])
		date := string(lines[1])
		summary := string(lines[2])
		body := strings.Join(lines[3:len(lines)], "\n")
		body = string(blackfriday.MarkdownCommon([]byte(body)))
		a = append(a, Post{title, date, summary, body, file})
	}
	return a
}
func main() {
	http.HandleFunc("/", handlerequest)
	http.ListenAndServe(":8000", nil)
}